import { Avatar, FormRule, PrimaryTableCol, Space, TableRowData } from 'tdesign-vue-next';

import { ActionBarItem } from '@/components/common-action-bar/index.vue';
import { t } from '@/locales';
import { tableActionBtn } from '@/utils/action';

export interface FormItem {
  id?: number;
  avatar: Recordable;
  roles: number[];
  realname: string;
  username: string;
  password: string;
  email?: string;
  phoneNumber?: string;
}

export const ACTION_BAR_DATA: ActionBarItem[] = [
  { text: 'common.add', theme: 'primary', auth: ['system:manager:create'], key: 'addShow' },
];

export const COLUMNS: PrimaryTableCol<TableRowData>[] = [
  { title: 'ID', colKey: 'id', width: 100 },
  {
    title: () => t('pages.manage.avatar'),
    colKey: 'avatar',
    cell(h, { row: { username, avatarUrl } }) {
      return h(Avatar, {
        image: avatarUrl,
        default: username.charAt(0).toUpperCase(),
        size: '36px',
        imageProps: {
          fit: 'cover',
        },
      });
    },
  },
  { title: () => t('pages.manage.account'), colKey: 'username', width: 180 },
  { title: () => t('pages.manage.role'), colKey: 'roleName', width: 180 },
  { title: () => t('pages.manage.realname'), colKey: 'realname', width: 180 },
  { title: () => t('pages.manage.phone'), colKey: 'phoneNumber', width: 180 },
  { title: () => t('pages.manage.email'), colKey: 'email', width: 180 },
  { title: () => t('common.createAt'), colKey: 'createdAt', width: 180 },
  { title: () => t('pages.manage.lastIp'), colKey: 'lastLoginIp', width: 180 },
  { title: () => t('pages.manage.lastAt'), colKey: 'lastLoginTime', width: 180 },
  {
    title: () => t('common.operation'),
    colKey: 'action',
    width: 260,
    fixed: 'right',
    cell(h, { row }) {
      const actionEdit = tableActionBtn({ h, type: 'edit', row, auths: ['system:manager:detail'] });
      const actionReset = tableActionBtn({
        h,
        type: 'resetpass',
        row,
        auths: ['system:manager:reset-pass'],
        theme: 'warning',
      });
      const actionDelete = tableActionBtn({ h, type: 'delete', row, auths: ['system:manager:delete'] });
      return h(Space, () => {
        return [actionEdit, actionReset, actionDelete];
      });
    },
  },
];

export const FORM_DATA: FormItem = {
  id: 0,
  avatar: {},
  roles: [],
  realname: '',
  username: '',
  password: '',
  email: '',
  phoneNumber: '',
};

export const FORM_RULES: Record<string, FormRule[]> = {
  roles: [{ required: true }],
  realname: [{ required: true }, { min: 2, max: 30, message: t('common.lengthBetween', { min: 2, max: 30 }) }],
  username: [{ required: true }, { min: 3, max: 30, message: t('common.lengthBetween', { min: 3, max: 30 }) }],
  password: [{ required: true }, { min: 5, max: 20, message: t('common.lengthBetween', { min: 6, max: 20 }) }],
};
